package com.neuedu.mblog.service;

import com.neuedu.mblog.dao.*;
import com.neuedu.mblog.entiry.*;
import com.neuedu.mblog.framework.Constants;
import com.neuedu.mblog.utils.BlogUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.*;

/**
 * 项目：mblog_java4
 * 创建时间：  2021-12-29   9:21
 * 作者 :jshand
 * 描述 :
 */
public class PostService {
    private UserDao userDao = new UserDao();
    private PostDao postDao = new PostDao();
    private TagDao tagDao= new TagDao();
    private PostTagDao postTagDao= new PostTagDao();
    private CommentDao commentDao= new CommentDao();


    /**
     * 查询集合不分页
     * @param request
     * @return
     */
    public List<Post> selectList(HttpServletRequest request) throws SQLException {
        //
        String sql = " SELECT  id,author_id,channel_id,comments,created,favors,featured,status,summary,tags,thumbnail,title,views,weight from mto_post ";
        return postDao.selectList(sql ,null);
    }


    /**
     * 修改前查询数据
     * @param request
     * @return
     * @throws SQLException
     */
    public Post selectById(HttpServletRequest request) throws SQLException {
        String id = request.getParameter("id");
        return postDao.selectById(Integer.parseInt(id));
    }

    public boolean update(HttpServletRequest request) throws SQLException {

        String id = request.getParameter("id");
        Post post  = postDao.selectById(Integer.parseInt(id));


        //管理员编辑的时候只允许编辑 如下字段
        post.setChannelId(Integer.parseInt(request.getParameter("channelId")));
        post.setStatus (Integer.parseInt(request.getParameter("status")));

        //原始markdown内容
        post.setSummary(request.getParameter("summary"));

        post.setTags(request.getParameter("tags"));
        post.setThumbnail(request.getParameter("thumbnail"));
        post.setTitle(request.getParameter("title"));

        return postDao.update(post) >0;
    }

    public boolean save(HttpServletRequest request) throws SQLException {
        Post post = new Post();

        //当前登录的用户
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        post.setAuthorId(user.getId());
        post.setChannelId(Integer.parseInt(request.getParameter("channelId")));
        post.setStatus (Integer.parseInt(request.getParameter("status")));


        post.setSummary(request.getParameter("summary"));
        post.setTags(request.getParameter("tags"));
//        post.setThumbnail(request.getParameter("thumbnail"));
        post.setTitle(request.getParameter("title"));
        post.setComments(0);
        post.setCreated(new Date());
        post.setFavors(0);
        post.setFeatured(0);
        post.setViews (0);
        post.setWeight (0);
        
        
        //保存文章额外需要保存下 标签


        boolean b1 = postDao.save(post) >0;
        long postId = post.getId();

        //生成标签
//        1 mto_tag 所有标签的信息
        String tags = post.getTags();
        String[] tagsArray = tags.split(",");
        String sql ="SELECT * FROM mto_tag   WHERE NAME=  ?";
        for (String name : tagsArray) {
            // 如果标签已经存在，则更新
            List<Tag> tagList = tagDao.selectList(sql, new Object[]{name});
            Tag tagEntity = null;

            //如果有标签则更新
            if(tagList.size()>0){
                tagEntity = tagList.get(0);

                tagEntity.setLatestPostId(postId);
                tagEntity.setPosts(tagEntity.getPosts()+1);//发帖数量增加
                tagEntity.setUpdated(new Date());
                tagDao.update(tagEntity);
            }else{
                //如果没有则新增一个标签
                tagEntity = new Tag();
                tagEntity.setCreated(new Date());
                tagEntity.setLatestPostId(postId);
                tagEntity.setName(name);
                tagEntity.setPosts(1);
                tagEntity.setUpdated(new Date());
                tagDao.save(tagEntity);
            }


            //2新增一个 文章 和 标签的对应关系
            PostTag postTag = new PostTag();
            postTag.setPostId(postId);
            postTag.setTagId( tagEntity.getId());
            postTagDao.save(postTag);

        }

        return b1;
    }

    public boolean deleteById(HttpServletRequest request) throws SQLException {
        String id = request.getParameter("id");
        return postDao.delete(Integer.parseInt(id))>0;
    }





    public void pageList(HttpServletRequest request) throws SQLException, ClassNotFoundException {
        Integer pageNum = 1;
        Integer pageSize = 10;


        String strPageNum = request.getParameter("pageNum");
        String strPageSize = request.getParameter("pageSize");
        if(strPageNum !=null && !"".equals(strPageNum)){
            pageNum =  Integer.parseInt(strPageNum);
        }
        if(strPageSize !=null && !"".equals(strPageSize)){
            pageSize =  Integer.parseInt(strPageSize);
        }


        //当前登录的用户
        User user = (User) request.getSession().getAttribute("user");

        String sql = "SELECT  id,author_id,channel_id,comments,created,favors," +
                "featured,status,summary,tags,thumbnail,title,views,weight from mto_post " +
                "where  author_id = ? ";




        ArrayList paramList = new ArrayList();
        paramList.add(user.getId());

        //select count(1) from (sql)
        long total = postDao.total(sql ,paramList.toArray());
        long pageCount = total%pageSize == 0?total/pageSize:(total/pageSize)+1;

        sql  += " limit  ? ,?";
        paramList.add((pageNum-1) * pageSize);
        paramList.add(pageSize);

        List<Post> pageList = postDao.selectList(sql,paramList.toArray());

        //使用request共享数据
        request.setAttribute("list",pageList);
        request.setAttribute("total",total);
        request.setAttribute("pageNum",pageNum);
        request.setAttribute("pageSize",pageSize);
        request.setAttribute("pageCount",pageCount);

//        System.out.println("total = " + total);
//        System.out.println("pageCount = " + pageCount);
//        System.out.println("pageSize = " + pageSize);
//        System.out.println("pageNum = " + pageNum);
//        System.out.println("list = " + pageList);


    }


    /**
     * 查看详情的
     * @param request
     */
    public void detail(HttpServletRequest request) throws SQLException {
        String id = request.getParameter("id");

        Post post  = postDao.selectById(Integer.parseInt(id));

        User user = userDao.selectById(Long.valueOf(post.getAuthorId()).intValue());

        //作者id
        Object params[] = new Object[]{user.getId()};

        String sql1 = "SELECT COUNT(1) FROM mto_post  t WHERE author_id = ? ";
        String sql2 = "SELECT COUNT(1) FROM mto_comment  t WHERE author_id = ? ";
        Long postCount = postDao.count(sql1,params);
        Long commentCount = commentDao.count(sql2,params);

        //标签列表
        List<Tag> tagList = tagDao.selectList(
                "select * from mto_tag where latest_post_id = ?",
                new Object[]{post.getId()}
        );

        //评论
        List<Comment> commentList = commentDao.selectList(
                "select * from mto_comment where post_id = ?",
                new Object[]{post.getId()}
        );


        request.setAttribute("postCount",postCount);
        request.setAttribute("commentCount",commentCount);
        request.setAttribute("post_user",user);
        request.setAttribute("post",post);
        request.setAttribute("tagList",tagList);
        request.setAttribute("commentList",commentList);


        //阅读量+1
        post.setViews(post.getViews()+1);
        postDao.update(post);

    }


    public void top(HttpServletRequest request) throws SQLException {
        String sql = "SELECT  id,author_id,channel_id,comments,created,favors," +
                "featured,status,summary,tags,thumbnail,title,views,weight from mto_post " +
                " ORDER BY  views DESC ,created DESC   LIMIT 5 ";




        String sql2 = "SELECT  id,author_id,channel_id,comments,created,favors," +
                "featured,status,summary,tags,thumbnail,title,views,weight from mto_post " +
                " order by created DESC   LIMIT 5 ";

        String sql3 = "select * from mto_comment ORDER BY created DESC   LIMIT 5  ";

        //点击量最多的  前五个
        List<Post> hotPost =  postDao.selectList(sql,null);


        //最新发布的   前五个
        List<Post> newPost =  postDao.selectList(sql2,null);


        //最新评论的前五个
        List<Comment> commentList = commentDao.selectList(sql3, null);


        request.setAttribute("hotPost",hotPost);
        request.setAttribute("newPost",newPost);
        request.setAttribute("topCommentList",commentList);



    }

    /**
     * 保存评论的
     * @param request
     * @return
     */
    public boolean saveComment(HttpServletRequest request) throws SQLException {
        //当前登录的用户
        User user = (User) request.getSession().getAttribute("user");


        Comment comment = new Comment();
        comment.setPostId(Integer.parseInt(request.getParameter("post_id")));
        comment.setAuthorId(user.getId());
        comment.setContent(request.getParameter("content"));
        comment.setCreated(new Date());//发表评论的时间（当前时间）
        comment.setPid(0);
        comment.setStatus(0);

        //评论数量加1
        Post post = postDao.selectById((int)comment.getPostId());
        post.setComments(post.getComments()+1);
        postDao.update(post);


        return  commentDao.save(comment) > 0 ;
    }

    public Map collect(HttpServletRequest request) throws SQLException {

        Map map = new HashMap();
        FavoriteDao favoriteDao  = new FavoriteDao();
        //当前登录的用户
        User user = (User) request.getSession().getAttribute("user");
        int postId = Integer.parseInt(request.getParameter("post_id"));

        //判断是否收藏过



        String sql = " select count(1) from mto_favorite where post_id = ?  and user_id = ?";
        long count = favoriteDao.count(sql, new Object[]{postId , user.getId() });
        if(count >0){
            map.put("success",false);
            map.put("msg","已经收藏过了，不要重复收藏");
            return map;
        }



        Favorite favorite = new Favorite();
        favorite.setCreated(new Date());
        favorite.setUserId(user.getId());
        favorite.setPostId(postId);




        //收藏数量加1
        Post post = postDao.selectById(postId);
        post.setFavors(post.getFavors()+1);
        postDao.update(post);

        boolean success = favoriteDao.save(favorite) >0;
        map.put("success",success);

        return map;
    }
}
